<template>
	<div>
		<div class="form-container">
			<el-form :model="form" ref="form" label-width="220px" label-position="right" :rules="rules">
				<v-form-title title="上传证件"/>
				<el-form-item prop="certType" label="证件类型">
					<el-radio-group v-model="form.certType" @change="rules.images[0].len=form.certType+3">
						<el-radio :label="0">多证合一营业执照（统一社会信用代码）</el-radio>
						<el-radio :label="1">多证合一营业执照（存在独立的组织机构代码证号）</el-radio>
						<el-radio :label="2">普通营业执照</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item prop="socialCreditCode" label="社会统一代码证">
					<el-input v-model="form.socialCreditCode" placeholder="请输入社会统一代码证号码" class="line-input"></el-input>
				</el-form-item>
				<el-form-item prop="businessLicenseNumber" label="营业执照注册号" v-if="form.certType !== 0">
					<el-input v-model="form.businessLicenseNumber" @change="getBusNum()" placeholder="请输入营业执照注册号码"
										class="line-input"></el-input>
				</el-form-item>
				<el-form-item prop="organizationCode" label="组织机构代码证" v-if="form.certType !== 0">
					<el-input v-model="form.organizationCode" placeholder="请输入组织机构代码证号码" class="line-input"></el-input>
				</el-form-item>
				<el-form-item prop="businessLicenseName" label="营业执照名称">
					<el-input v-model="form.businessLicenseName" placeholder="请输入营业执照名称" class="line-input"></el-input>
				</el-form-item>
				<el-form-item prop="taxpayerName" label="纳税人名称">
					<el-input v-model="form.taxpayerName" placeholder="请输入纳税人名称" class="line-input"></el-input>
				</el-form-item>
				<el-form-item prop="establishmentDate" label="成立日期">
					<el-date-picker
							class="line-input"
							v-model="form.establishmentDate"
							type="date"
							placeholder="成立日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item prop="expirationDate" label="失效日期">
					<el-date-picker
							class="line-input"
							v-model="form.expirationDate"
							type="date"
							placeholder="失效日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item prop="images">
					<v-unit-auth-images :images="images" v-model="form.images" @ocr="licenseOcr" @idCardOcr="idCardOcr"/>
				</el-form-item>
				<v-form-title title="企业信息"/>
				<el-form-item prop="enterpriseName" label="企业名称">
					<el-input class="line-input" v-model="form.enterpriseName" placeholder="请输入企业名称"></el-input>
				</el-form-item>
				<el-form-item prop="addressArray" label="通讯地址">
					<v-address ref="address" v-model="form.addressArray"></v-address>
				</el-form-item>
				<el-form-item prop="legalRepresentative" label="法定代表人姓名">
					<el-input class="line-input" v-model="form.legalRepresentative" placeholder="请输入法定代表人姓名"></el-input>
				</el-form-item>
				<el-form-item prop="legalCertType" label="法定代表人证件类型">
					<el-select v-model="form.legalCertType" placeholder="请选择法定代表人证件类型">
						<el-option
								v-for="item in $dict.legalTypes"
								:key="item.value"
								:label="item.label"
								:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<!--<el-form-item prop="legalCertType" label="法定代表人证件类型">-->
					<!--<el-select v-model="form.legalCertType" placeholder="请选择法定代表人证件类型">-->
						<!--<el-option-->
								<!--v-for="item in $dict.legalTypes"-->
								<!--:key="item.value"-->
								<!--:label="item.label"-->
								<!--:value="item.value">-->
						<!--</el-option>-->
					<!--</el-select>-->
				<!--</el-form-item>-->
				<el-form-item prop="legalCertNo" label="法定代表人证件号码">
					<el-input class="line-input" v-model="form.legalCertNo" placeholder="请输入法定代表人证件号码"></el-input>
				</el-form-item>
				<el-form-item prop="legalAddressArray" label="法定代表人归属地">
					<v-address ref="legalAddressArray" v-model="form.legalAddressArray"></v-address>
				</el-form-item>
				<el-form-item prop="address" label="详细地址">
					<el-input class="line-input" v-model="form.address" placeholder="请输入详细地址"></el-input>
				</el-form-item>
				<el-form-item prop="industryType" label="行业类型">
					<el-select v-model="form.industryType" placeholder="请选择行业类型">
						<el-option
								v-for="item in $dict.industryTypes"
								:key="item.value"
								:label="item.label"
								:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item prop="enterpriseType" label="企业类型">
					<el-select v-model="form.enterpriseType" placeholder="请选择企业类型">
						<el-option
								v-for="item in $dict.enterpriseTypes"
								:key="item.value"
								:label="item.label"
								:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属渠道商">
					{{form.affiliation}}
				</el-form-item>
				<el-form-item label="推荐人">
					{{form.recommendedManagerName}}
				</el-form-item>
			</el-form>
		</div>
		<div class="operation">
			<el-button type="primary" @click="valid" v-if="this.userInfo.certificationStatus < 1 && this.form.agencyCertificationStatus === 1" disabled>提交</el-button>
			<el-button type="primary" @click="valid" v-if="this.userInfo.certificationStatus < 1 && this.form.agencyCertificationStatus !== 1">提交</el-button>
		</div>
	</div>
</template>
<script lang="ts">
    import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
    import { Action } from 'vuex-class'
    import vAddress from '@/components/address'
    import vUnitAuthImages from '@/components/unit-auth-images'
    import vFormTitle from '@/components/form-title'

    @Component({
        components: {
            vAddress,
            vUnitAuthImages,
            vFormTitle
        }
    })
    export default class Step1 extends Vue {
        @Action getPolicy
        @Prop() userInfo

        mounted () {

            this.getPolicy()
        }
        esDate = ''
        exDate = ''
        async post (form) {
            // 处理日期
            // console.log(typeof form.establishmentDate)
            // if(!JSON.parse(window.localStorage.getItem('invite')) || JSON.parse(window.localStorage.getItem('invite')) === null){
            //
            // }
            form.enterpriseUserId = JSON.parse(window.sessionStorage.getItem('certicaDetail')).id
            // console.log(form)
            if(typeof form.establishmentDate == 'string'){
                this.esDate = this.$utils.getTimeNum(form.establishmentDate)
                this.exDate = this.$utils.getTimeNum(form.expirationDate)
            }else{
                this.esDate = +form.establishmentDate
                this.exDate = +form.expirationDate
            }
						// console.log(this.esDate)
            // console.log(this.exDate)
            let res: AjaxResponse = await this.$axios.post('g/gateway/member/agencycertification', {
                ...form,
                establishmentDate: this.esDate,
                expirationDate: this.exDate
            })
            this.$utils.tips(res)

        }
        form = {
            certType: 0,
            socialCreditCode: '',
            businessLicenseNumber: '',
            businessLicenseName: '',
            establishmentDate: '',
            expirationDate: '',
            taxpayerName: '',
            organizationCode: '',
            images: [],
            affiliation: '',
            recommendedManagerName: '',
            enterpriseUserId: '',
            //
            enterpriseName: '',
            addressArray: [],
            address: '',
            industryType: '',
            enterpriseType: '',
            legalRepresentative: '',
            legalCertNo: '',
            legalAddressArray: [],
            legalCertType: ''
        }
        tempForm = {}
        rules = {
            certType: [{ required: true, message: '请选择营业执照类型', trigger: 'change' }],
            industryType: [{ required: true, message: '请选择行业类型', trigger: 'change' }],
            enterpriseType: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
            socialCreditCode: [
            	{ required: true, message: '请输入社会统一代码证号码', trigger: 'change' },
            	{
								pattern: /[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}/g,
								message: '统一社会信用代码错误',
								trigger: 'blur'
            	}
            ],
            taxpayerName: [{ required: true, message: '请输入纳税人名称', trigger: 'change' }],
            businessLicenseName: [{ required: true, message: '请输入营业执照名称\n', trigger: 'change' }],
            address: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
            businessLicenseNumber: [{ required: true, message: '请输入营业执照注册号码', trigger: 'change' }],
            expirationDate: [{ required: true, message: '请选择失效日期', trigger: 'change' }],
            establishmentDate: [{ required: true, message: '请选择成立日期', trigger: 'change' }],
            // organizationCode: [{ required: true, message: '请输入组织机构代码证号码', trigger: 'change' }],
            images: [{ type: 'array', required: true, message: '请上传相应的图片', trigger: 'change', len: 3 }],
            //
            enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
            legalRepresentative: [{ required: true, message: '请输入法定代表人姓名', trigger: 'blur' }],
            legalCertNo: [{ required: true, message: '请输入法定代表人证件号码', trigger: 'blur' }],
            legalCertType: [{ required: true, message: '请输入法定代表人证件类型', trigger: 'blur' }],
            addressArray: [{ type: 'array', required: true, message: '请选择企业通讯地址', trigger: 'change', len: 3 }],
            legalAddressArray: [{ type: 'array', required: true, message: '请选择法定代表人归属地', trigger: 'change', len: 3 }]
        }

        imagesMap = [
            {
                key: 'businessLicensePhoto',
                src: '',
                name: '营业执照正本',
                placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/fddde45b-2132-4e75-84ef-dcc983fe128b.png',
                certType: 0
            },
            {
                key: 'legalFrontPhoto',
                src: '',
                name: '法定代表人身份证正面',
                placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/61afb7a6-904b-43fe-93f3-efc4f713cf08.png',
                certType: 0
            },
            {
                key: 'legalBackPhoto',
                src: '',
                name: '法定代表人身份证背面',
                placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/f730fa6a-ca7b-4a57-9944-40b3c861fe29.png',
                certType: 0
            },
            {
                key: 'organizationCodePhoto',
                src: '',
                name: '组织机构代码证',
                placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/2020d070-b61b-429f-99c2-3276572f2744.png',
                certType: 1
            },
            {
                key: 'taxRegistrationPhoto',
                src: '',
                name: '税务机构登记证',
                placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/0fcef1e4-94e5-472e-b54e-6bf8d6f23592.png',
                certType: 2
            }
        ]

        get images () {
            return this.imagesMap.filter(image => this.form.certType >= image.certType)
        }

        valid () {
            this.$refs.form.validate(valid => {
                // if (!valid) return
                let f = { ...this.form }
                f.areaProvince = f.addressArray[0]
                f.areaCity = f.addressArray[1]
                f.areaDistrict = f.addressArray[2]
                f.legalProvince = f.legalAddressArray[0]
                f.legalCity = f.legalAddressArray[1]
                f.legalDistrict = f.legalAddressArray[2]
                f.channelProviderId = window.sessionStorage.getItem('enterpriseUserId')
                f.enterpriseInfoId = this.userInfo.enterpriseInfoId
                f.images.forEach(v => {
                    f[v.key] = v.src
                })
                delete  f.images
                delete  f.addressArray
                delete  f.legalAddressArray
                for (let key in f) {
                    if (f.hasOwnProperty(key)) {
                        if (f[key] === null || f[key] === '') {
                            delete f[key]
                        }
                    }
                }
                this.post(f)
            })
        }

        @Watch('userInfo')
        c (userInfo) {
            this.tempForm = { ...userInfo }
            this.platForm()
        }

        async getBusNum () {

        }

        mounted () {
            this.getPolicy()
            let invite = JSON.parse(window.localStorage.getItem('invite'))
            if (invite) {
                this.form.affiliation = invite.affiliation
                this.form.recommendedManagerName = invite.managerName
                // this.form.enterpriseUserId = invite.enterpriseUserId
            }else{
                // this.form.enterpriseUserId = JSON.parse(window.sessionStorage.getItem('certicaDetail')).id
            }
            if (this.userInfo.id) {
                this.c(this.userInfo)
            }
        }

        platForm () {
            for (let key in this.tempForm) {
                if (this.tempForm.hasOwnProperty(key)) {
                    this.form[key] = this.tempForm[key]
                }
            }
            this.rules.images[0].len = this.tempForm.certType + 3
            this.imagesMap.forEach(item => {
                item.src = this.tempForm[item.key]
            })
            this.form.images = this.imagesMap.filter(v => v.src)
            this.$refs.address.init([this.tempForm.areaProvince, this.tempForm.areaCity, this.tempForm.areaDistrict])
            this.$refs.legalAddressArray.init([this.tempForm.legalProvince, this.tempForm.legalCity, this.tempForm.legalDistrict])
        }

        async licenseOcr (imageUrl) {
            let res: AjaxResponse = await this.$axios.post('g/gateway/ocr/business/license', {
                imageUrl
            })
            if (res.responseCode === 200) {
                this.form.address = res.data.address
                this.form.socialCreditCode = res.data.reg_num
                this.form.businessLicenseNumber = res.data.reg_num
                this.form.legalRepresentative = res.data.person
                this.form.establishmentDate = +new Date(res.data.establish_date.replace(/(.{4})/, '$1-').replace(/(.{7})/, '$1-'))
                this.form.expirationDate = +new Date(res.data.valid_period.replace(/(.{4})/, '$1-').replace(/(.{7})/, '$1-'))
                this.form.enterpriseName = res.data.name
                this.form.businessLicenseName = res.data.name
                if(res.data.reg_num !== undefined) {
                	let strLength = (res.data.reg_num).length -1
                	this.form.organizationCode = (res.data.reg_num).substring(8,strLength)
                }
                // this.form.organizationCode = (res.data.businessLicenseNumber).substr(9,(res.data.businessLicenseNumber).length - 2)
            }
        }

        async idCardOcr (imageUrl) {
            let res: AjaxResponse = await this.$axios.post('g/gateway/ocr/idcard', {
                faceOrBack: 'face',
                imageUrl
            })
            if (res.responseCode === 200) {
                this.form.legalRepresentative = res.data.name
                this.form.legalCertNo = res.data.id_num
                // this.form.legalCertType = '1'
                // this.form.legalType = '1'
                this.form.address = res.data.address
            }
        }

        // mounted () {
        //     if (this.userInfo.id) {
        //         this.c(this.userInfo)
        //     }
        // }

        // async post (form) {
        //     let res: AjaxResponse = await this.$axios.post('g/gateway/member/agencycertification', {
        //         ...form,
        //         establishmentDate: +form.establishmentDate,
        //         expirationDate: +form.expirationDate
        //     })
        //     window.sessionStorage.setItem('enterpriseName',this.form.enterpriseName)
        //     this.$utils.tips(res)
        //     if (res.responseCode === 200) {
        //         this.$router.push('/register/step-2')
        //     }
        // }
    }
</script>
<style lang="less" scoped>
	.form-container {
		width: 1180px;
		margin: 0 auto;
		padding: 60px 0 30px;
	}

	.operation {
		text-align: center;
		font-size: 14px;
		color: #999;
		.el-button {
			margin: 30px 0;
		}
	}

	.el-steps {
		margin-bottom: 60px;
	}
</style>
